package com.example.demo.zaqizabatest;

import java.util.concurrent.*;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @ClassName SimpleResourceManager
 * @Author l42142
 * @Date 2021/3/3 11:39
 * @Description TODO
 * @Version 1.0
 **/
public class SimpleResourceManager {
    private final InnerSynchronizer synchronizer;

    private static class InnerSynchronizer extends AbstractQueuedSynchronizer {
        InnerSynchronizer(int numOfResources) {
            setState(numOfResources);
        }

        @Override
        protected int tryAcquireShared(int acquires) {
            for (; ; ) {
                int available = getState();
                int remain = available - acquires;
                if (remain < 0 || compareAndSetState(available, remain)) {
                    return remain;
                }
            }
        }

        @Override
        protected boolean tryReleaseShared(int releases) {
            for (; ; ) {
                int available = getState();
                int next = available + releases;
                if (compareAndSetState(available, next)) {
                    return true;
                }
            }
        }
    }

    public SimpleResourceManager(int numOfResources) {
        synchronizer = new InnerSynchronizer(numOfResources);
    }

    public void acquire() throws InterruptedException {
        synchronizer.acquireSharedInterruptibly(1);
    }

    public void release() {
        synchronizer.releaseShared(1);
    }

    public static void main(String[] args) {
        BlockingQueue blockingQueue = new LinkedBlockingQueue(3);
        blockingQueue.add("1");blockingQueue.add("2");blockingQueue.add("3");
        blockingQueue.poll();
        BlockingDeque blockingDeque = new LinkedBlockingDeque();

    }

}
